package com.timer.taskRule.controller;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import com.timer.taskRule.entity.TaskRule;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.util.DigestUtils;

import java.io.*;
import java.nio.file.*;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

public class FileListener extends FileAlterationListenerAdaptor {


    /**
     * 文件创建执行
     */
    public void onFileCreate(File file) {
        System.out.println("[新建文件]:" + file.getAbsolutePath());
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file.getAbsolutePath());
            String s = DigestUtils.md5DigestAsHex(fileInputStream);
            System.out.println(s);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fileInputStream != null) fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 文件创建修改
     */
    public void onFileChange(File file) {
        System.out.println("[修改文件]:" + file.getAbsolutePath());
    }

    /**
     * 文件删除
     */
    public void onFileDelete(File file) {
        System.out.println("[删除文件]:" + file.getAbsolutePath());
    }

    /**
     * 目录创建
     */
    public void onDirectoryCreate(File directory) {
        System.out.println("[新建目录]:" + directory.getAbsolutePath());
    }

    /**
     * 目录修改
     */
    public void onDirectoryChange(File directory) {
        System.out.println("[修改目录]:" + directory.getAbsolutePath());
    }

    /**
     * 目录删除
     */
    public void onDirectoryDelete(File directory) {
        System.out.println("[删除目录]:" + directory.getAbsolutePath());
    }

    public void onStart(FileAlterationObserver observer) {
        super.onStart(observer);
        //System.out.println("文件监控服务已启动！！");
    }

    public void onStop(FileAlterationObserver observer) {
        super.onStop(observer);
       // System.out.println("文件监控服务已关闭！！");
    }


    public static void start(){
        FileAlterationMonitor monitor = null;
        // 监控目录
        String rootDir = "E:\\file";
        // 轮询间隔 5 秒
        long interval = TimeUnit.SECONDS.toMillis(1);

        // 创建过滤器
        IOFileFilter directories = FileFilterUtils.and(
                FileFilterUtils.directoryFileFilter(),
                HiddenFileFilter.VISIBLE);
        IOFileFilter files       = FileFilterUtils.and(
                FileFilterUtils.fileFileFilter(),
                FileFilterUtils.suffixFileFilter(".txt"));
        IOFileFilter filter = FileFilterUtils.or(directories, files);

        // 使用过滤器
        FileAlterationObserver observer = new FileAlterationObserver(new File(rootDir), filter);
        //不使用过滤器
        //FileAlterationObserver observer = new FileAlterationObserver(new File(rootDir));
        observer.addListener(new FileListener());

        //创建文件变化监听器
         monitor = new FileAlterationMonitor(interval, observer);
        // 开始监控
        try {
            monitor.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        TaskRule instance = TaskRule.getInstance();
        instance.put("111","111");
        instance = null;
        TaskRule instance2 = TaskRule.getInstance();


        System.out.println("启动监控服务前");

        String path = "E:\\file";
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                WatchKey key;
                try {
                    WatchService watchService = FileSystems.getDefault().newWatchService();
                    Paths.get(path).register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
                    while (true) {
                        File file = new File(path);//path为监听文件夹
                        File[] files = file.listFiles();
                        System.out.println("等待图片加载！");
                        key = watchService.take();//没有文件增加时，阻塞在这里
                        for (WatchEvent<?> event : key.pollEvents()) {
                            String fileName = path+"\\"+event.context();
                            System.out.println("增加文件的文件夹路径"+fileName);
                            File file1 = files[files.length-1];//获取最新文件
                            System.out.println(file1.getName());//根据后缀判断
                        }if (!key.reset()) {
                            break; //中断循环
                        }
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 2000 , 3000);//第一个数字2000表示，2000ms以后开启定时器,第二个数字3000，表示3000ms后运行一次run


        /*new Thread(new Runnable() {
            @Override
            public void run() {
                FileAlterationMonitorInstances instances = new FileAlterationMonitorInstances("E:\\file",3000,new FileListener());
                try {
                    instances.monitor().start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();*/

       /* new Thread(new Runnable() {
            @Override
            public void run() {

                File file = new File("E:\\file\\aaa\\abc.txt");
                try {
                    Thread.sleep(5000);
                    FileWriter fileWriter = new FileWriter(file);
                    fileWriter.write("");
                    System.out.println("创建文件完成");
                    Thread.sleep(50);
                    fileWriter.close();
                    if(file.exists()){
                        file.delete();
                        System.out.println("删除文件完成");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();*/

        System.out.println("启动监控服务后");
    }
}
